package com.bqtv.sport.commen.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import java.util.ArrayList;
import java.util.List;

public class LuckWheelView  extends View {
    Path path  = new Path();
    private final DisplayMetrics mDM;
    private TextPaint mArcPaint;
    private TextPaint mDrawerPaint;
    private int maxRadius;
    private float perDegree;
    private long duration = 5000L;
    private List<Item> items = new ArrayList<>();
    private RectF rectF = new RectF();
    private float offsetDegree = 0;
    private TimeInterpolator timeInterpolator = new AccelerateDecelerateInterpolator();
    private long speedTime = 1000L; //旋转一圈需要多少时间
    private ValueAnimator animator = null;

    public LuckWheelView(Context context) {
        this(context, null);
    }

    public LuckWheelView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LuckWheelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mDM = getResources().getDisplayMetrics();
        initPaint();

    }

    public void setRotateIndex(int index) {
        if (items == null || items.size() <= index) {
            return;
        }

        //圆点起始角度 ，可以理解为index=0的起始角度，我们以index=0位参考点
        float zeroStartDegree = 0 + -perDegree / 2;
        float endStartDegree = 0 + perDegree / 2;

        //从圆点计算，要旋转的角度
        float targetDegree = (perDegree * (index - 1) + perDegree / 2);
        float rotateDegree = zeroStartDegree - targetDegree;

        //防止逆时针旋转 （三角函数定理  n*360 + degree 和 degree最终夹角是等价的 ）
        while (rotateDegree < offsetDegree) {
            rotateDegree += 360;
        }
        if (speedTime == 0) {
            speedTime = 100L;
        }
        long count = duration / speedTime - 1;  //计算额外旋转圈数
        while (count >= 0) {
            rotateDegree += 360;  //三角函数定理  n*360 + degree 和 degree最终夹角是等价的
            count--;
        }

        float targetStartDegree = rotateDegree - perDegree / 2;
        float targetEndDegree = rotateDegree + perDegree / 2;

        float currentOffsetDegree = offsetDegree;
        // float targetOffsetDegree  = (targetStartDegree +  targetEndDegree)/2 ;
        //让指针指向有一定的随机性
        float targetOffsetDegree = (float) (targetStartDegree + (targetEndDegree - targetStartDegree) * Math.random());

        if (animator != null) {
            animator.cancel();
        }
//起点肯定要从当前角度算起，不然会闪一下回到原点
        animator = ValueAnimator
                .ofFloat(currentOffsetDegree, targetOffsetDegree)
                .setDuration(duration);
        animator.setInterpolator(timeInterpolator);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                offsetDegree = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                offsetDegree = offsetDegree % 360;
            }
        });
        animator.start();
    }

    private void initPaint() {
        // 实例化画笔并打开抗锯齿
        mArcPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        mArcPaint.setAntiAlias(true);
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setStrokeCap(Paint.Cap.ROUND);

        mDrawerPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        mDrawerPaint.setAntiAlias(true);
        mDrawerPaint.setStyle(Paint.Style.FILL);
        mDrawerPaint.setStrokeCap(Paint.Cap.ROUND);
        mDrawerPaint.setStrokeWidth(5);
        mDrawerPaint.setTextSize(spTopx(14));

    }

    private float spTopx(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, dp, getResources().getDisplayMetrics());
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        if (widthMode != MeasureSpec.EXACTLY) {
            widthSize = mDM.widthPixels / 2;
        }

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (heightMode != MeasureSpec.EXACTLY) {
            heightSize = widthSize / 2;
        }
        setMeasuredDimension(widthSize, heightSize);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (width == 0 || height == 0 || items == null || items.size() <= 0) {
            perDegree = 0;
            return;
        }

        maxRadius = Math.min(width / 2, height / 2);
        rectF.left = -maxRadius;
        rectF.top = -maxRadius;
        rectF.right = maxRadius;
        rectF.bottom = maxRadius;

        int size = items.size();

        int saveCount = canvas.save();
        canvas.translate(width * 1F / 2, height * 1F / 2); //平移坐标轴到view中心点
        canvas.rotate(-90); //逆时针旋转坐标轴 90度
        perDegree = 360 * 1F / size;

        // rangeDegree = start ->end
        // rangeDegree.start = perDegree/2 + (i-1) * perDegree;
        // rangeDegree.end = perDegree/2 + (i) * perDegree;


        for (int i = 0; i < size; i++) {

            //由于我们让第一个区域的中心点对准x轴了，所以(i-1)意味着从y轴负方向顺时针转动
            float startDegree = perDegree * (i - 1) + perDegree / 2 + offsetDegree;
            float endDegree = i * perDegree + perDegree / 2 + offsetDegree;

            Item item = items.get(i);
            mDrawerPaint.setColor(item.color);
//            double startDegreeRandians = Math.toRadians(startDegree); //x1
//            float x = (float) (maxRadius * Math.cos(startDegreeRandians));
//            float y = (float) (maxRadius * Math.sin(startDegreeRandians));
//            canvas.drawLine(0,0,x,y,mDrawerPaint);

            float centerRadius = (float) Math.toRadians((startDegree + endDegree)/2F);
            float measuredTextWidth = mDrawerPaint.measureText(item.text);
            float measuredTextHeight = getTextHeight(mDrawerPaint,item.text);

            float innerRadius = maxRadius - 2* measuredTextHeight;

            float cx = (float) ((innerRadius - measuredTextHeight)   * Math.cos(centerRadius));
            float cy = (float) ((innerRadius - measuredTextHeight)  * Math.sin(centerRadius));

            double degreeOffset = Math.asin((measuredTextWidth/2F)/innerRadius);
            float startX= (float) (innerRadius * Math.cos(centerRadius - degreeOffset));
            float startY = (float) (innerRadius * Math.sin(centerRadius - degreeOffset));

            float endX= (float) ((innerRadius) * Math.cos(centerRadius + degreeOffset));
            float endY = (float) ((innerRadius) * Math.sin(centerRadius + degreeOffset));

            path.reset();
            path.moveTo(startX,startY);
            path.lineTo(endX,endY);
            //这里使用Path的原因是文本角度无法设置
            canvas.drawArc(rectF, startDegree, endDegree - startDegree, true, mDrawerPaint);
            mDrawerPaint.setColor(Color.WHITE);
            canvas.drawCircle(cx,cy,5,mDrawerPaint);
            canvas.drawTextOnPath(item.text,path,0,0,mDrawerPaint);
        }

        canvas.drawLine(0, 0, maxRadius / 2F, 0, mDrawerPaint);

        canvas.restoreToCount(saveCount);

    }


    Rect textBounds = new Rect();

    //真实宽度 + 笔画上下两侧间隙（符合文本绘制基线）
    private  int getTextHeight(Paint paint,String text) {
        paint.getTextBounds(text,0,text.length(),textBounds);
        return textBounds.height();
    }


    public void setItems(List<Item> items) {
        this.items.clear();
        this.items.addAll(items);
        invalidate();
    }

    public static class Item {
        Object tag;
        int color = Color.TRANSPARENT;
        String text;

        public Item(int color, String text) {
            this.color = color;
            this.text = text;
        }
    }
}
